//
//  UNBadgeView.m
//  Union
//
//  Created by xiaowuxiaowu on 16/7/21.
//  Copyright © 2016年 xiaowuxiaowu. All rights reserved.
//

#import "UNBadgeView.h"

@implementation UNBadgeView
-(instancetype)init{
 
    if(self = [super init]){
        [self setup];
    }
    return self;
}
-(void)willMoveToSuperview:(UIView *)newSuperview{
 
    [super willMoveToSuperview:newSuperview];
    
}
-(void)setup{
    self.backgroundColor   = [UIColor redColor];
    self.textColor = [UIColor whiteColor];
    self.font      = [UIFont systemFontOfSize:12.0];
    self.textAlignment = NSTextAlignmentCenter;
    
    self.layer.masksToBounds = YES;
    self.layer.cornerRadius = 10.f;
    self.size = CGSizeMake(20.0f, 20.0f);
    self.badgeX   = self.superview.width/2;
    self.badgeY   = 4;
    self.hidden = YES;
    self.shouldAnimateBadge = YES;
}
-(void)setBadgeX:(CGFloat)badgeX{
    _badgeX = badgeX;
    self.left = badgeX;
}
-(void)setBadgeY:(CGFloat)badgeY{
    _badgeY = badgeY;
    self.top = badgeY;
}
-(void)setBadgeValue:(NSString *)badgeValue{
    _badgeValue =badgeValue;
    if(!badgeValue || _badgeValue.length <=0 || [_badgeValue isEqualToString:@"0"]){
        [self removeBadge];
    
    }else if([badgeValue integerValue] > 9){
        self.width = 30.0f;
           [self updateBadgeValueAnimated:YES];
    }else{
        self.width = 20.f;
           [self updateBadgeValueAnimated:YES];
    }
    
 
}
// Handle the badge changing value
- (void)updateBadgeValueAnimated:(BOOL)animated
{
    
    self.hidden = NO;
    
        self.transform = CGAffineTransformMakeScale(1.0, 1.0);

    // Bounce animation on badge if value changed and if animation authorized
    if (animated && self.shouldAnimateBadge && ![self.text isEqualToString:self.badgeValue]) {
        CABasicAnimation * animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        [animation setFromValue:[NSNumber numberWithFloat:1.5]];
        [animation setToValue:[NSNumber numberWithFloat:1]];
        [animation setDuration:0.2];
        [animation setTimingFunction:[CAMediaTimingFunction functionWithControlPoints:.4f :1.3f :1.f :1.f]];
        [self.layer addAnimation:animation forKey:@"bounceAnimation"];
    }
    
    // Set the new value
    self.text = self.badgeValue;
    
    // Animate the size modification if needed
    NSTimeInterval duration = animated ? 0.2 : 0;
    [UIView animateWithDuration:duration animations:^{
       // [self updateBadgeFrame];
    }];
}

- (void)removeBadge
{
         self.hidden = YES;
    // Animate badge removal
//    [UIView animateWithDuration:0.2 animations:^{
//        self.transform = CGAffineTransformMakeScale(0, 0);
//    } completion:^(BOOL finished) {
//      
//        self.hidden = YES;
//    }];
}
@end
